<?php
/**
 * @author       Sixe Team
 * @email        info@eee-eee.com
 * @url          http://www.eee-eee.com
 * @copyright    Copyright (C) 2010 - 2019 Sixe Information Technology Limited. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @date         2019/10/01 10:00
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;


/**
 * Item Model for an Article.
 *
 * @since  1.6
 */
class SixeWorkFlowModelWorkFlow extends JModelAdmin
{
	/**
	 * The prefix to use with controller messages.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_SIXEWORKFLOW';

	/**
	 * The type alias for this content type (for example, 'com_content.article').
	 *
	 * @var    string
	 * @since  3.2
	 */
	public $typeAlias = 'com_sixeworkflow.workflow';



	





	/**
	 * Prepare and sanitise the table data prior to saving.
	 *
	 * @param   JTable  $table  A JTable object.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */


	/**
	 * Returns a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable    A database object
	 */
	public function getTable($type = 'WorkFlow', $prefix = 'SixeWorkFlowTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed  Object on success, false on failure.
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			$item->flows=$this->getFlows($item->id);
			$item->category_id=$this->getCategorys($item->id);

		}



		return $item;
	}


	public function getCategorys($id)
	{
		$catids=array();
		$db = $this->getDbo();
				$query = $db->getQuery(true);
				$query->select('category_id')
					->from('#__workflow_categories')
					->where('workflow_id ='.(int)$id);
					$db->setQuery($query);
				$catids=$db->loadColumn();
		return $catids;
	}


	public function getFlows($id)
	{
			$flows=array();
			if($id>0)
			{
				$db = $this->getDbo();
				$query = $db->getQuery(true);
				$query->select('*')
					  ->from('#__workflow_users')
					  ->where('workflow_id='.(int)$id)
					  ->order('flow_id ASC');
				$db->setQuery($query);
				$temp = $db->loadObjectList();
				foreach($temp as $t)
				{
					$flows[$t->flow_id]['title']=$t->title;
					$flows[$t->flow_id]['type']=$t->type;
					if($t->type==1)
					{
						$flows[$t->flow_id]['groups'][]=$t->user_id;
					}
					elseif($t->type==2)
					{
						$flows[$t->flow_id]['users'][]=$t->user_id;
					}
				}
			}
			return $flows;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		$app = JFactory::getApplication();
		$user = JFactory::getUser();

		// Get the form.
		$form = $this->loadForm('com_sixeworkflow.workflow', 'workflow', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}




		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$app  = JFactory::getApplication();
		$data = $app->getUserState('com_sixeworkflow.edit.workflow.data', array());

		if (empty($data))
		{
			$data = $this->getItem();


		}

		// If there are params fieldsets in the form it will fail with a registry object
		if (isset($data->params) && $data->params instanceof Registry)
		{
			$data->params = $data->params->toArray();
		}

		$this->preprocessData('com_sixeworkflow.workflow', $data);

		return $data;
	}

	/**
	 * Method to validate the form data.
	 *
	 * @param   JForm   $form   The form to validate against.
	 * @param   array   $data   The data to validate.
	 * @param   string  $group  The name of the field group to validate.
	 *
	 * @return  array|boolean  Array of filtered data if valid, false otherwise.
	 *
	 * @see     JFormRule
	 * @see     JFilterInput
	 * @since   3.7.0
	 */
	public function validate($form, $data, $group = null)
	{
		// Don't allow to change the users if not allowed to access com_users.


		return parent::validate($form, $data, $group);
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{

		$return=parent::save($data);
		
		if($return)
		{
			$this->saveCategorys($data);
			$recordId = $this->getState($this->getName().'.id');
			$db = $this->getDbo();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_users'))
					->where($query->qn('workflow_id') . ' = ' . (int) $recordId);
			$db->setQuery($query)->execute();
			$data=(object)$data;
			if(!empty($data->flows) && is_array($data->flows))
			{
				$users=array();
				$flows=array_values($data->flows);
				foreach($flows as $key=>$flow)
				{
					$flow=(object)$flow;
					if($flow->type==1)
					{
						if(!empty($flow->groups) && is_array($flow->groups))
						{
							foreach($flow->groups as $group)
							{
								$temp=new stdClass();
								$temp->workflow_id=(int) $recordId;
								$temp->flow_id=$key;
								$temp->type=$flow->type;
								$temp->user_id=$group;
								$temp->title=$flow->title;
								$users[]=$temp;
							}
						}

					}
					elseif($flow->type==2)
					{
						if(!empty($flow->users) && is_array($flow->users))
						{
							foreach($flow->users as $user)
							{
								$temp=new StdClass();
								$temp->workflow_id=(int) $recordId;
								$temp->flow_id=$key;
								$temp->type=$flow->type;
								$temp->user_id=$user;
								$temp->title=$flow->title;
								$users[]=$temp;
							}
						}
					}

				}
				$temp_users=array();
				foreach($users as $uobj)
				{
					
					$temp_obj=new stdClass;
					$temp_obj->workflow_id=$uobj->workflow_id;
					$temp_obj->type=$uobj->type;
					$temp_obj->user_id=$uobj->user_id;
					$temp_users[]=serialize($temp_obj);
				}
				$users_obj=array_unique($temp_users);
				foreach($users_obj as $key=>$obj)
				{

					try
					{
						$db->insertObject('#__workflow_users', $users[$key]);
					}
					catch(Exception $e)
 						{
							 echo 'Message: ' .$e->getMessage();
 						}
					
				}
			}
		}
		return $return;
	}

	

	function saveCategorys($data)
	{
		$data=(object)$data;
		$recordId = $this->getState($this->getName().'.id');
		if(isset($data->category_id) && is_array($data->category_id) && count($data->category_id))
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_categories'))
				->where('workflow_id ='.$recordId);
				$db->setQuery($query)->execute();
				foreach($data->category_id as $item)
				{
					$newObj = new stdClass;
					$newObj->category_id = (int) $item;
					$newObj->workflow_id  = $recordId;
					$db->insertObject('#__workflow_categories', $newObj);
				}
					
				
		}
		
	
	}


	/**
	 * Allows preprocessing of the JForm object.
	 *
	 * @param   JForm   $form   The form object
	 * @param   array   $data   The data to be merged into the form object
	 * @param   string  $group  The plugin group to be executed
	 *
	 * @return  void
	 *
	 * @since   3.0
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{

		parent::preprocessForm($form, $data, $group);
	}



	/**
	 * Void hit function for pagebreak when editing content from frontend
	 *
	 * @return  void
	 *
	 * @since   3.6.0
	 */
	public function hit()
	{
		return;
	}



	/**
	 * Delete #__content_frontpage items if the deleted articles was featured
	 *
	 * @param   object  $pks  The primary key related to the contents that was deleted.
	 *
	 * @return  boolean
	 *
	 * @since   3.7.0
	 */
	public function delete(&$pks)
	{
		$return = parent::delete($pks);



		return $return;
	}
}
